<template>
  <div class="change-psw">
    <el-form
      :model="userInfo"
      :rules="rules"
      ref="userForm"
      label-width="150px"
      size="small">
      <el-form-item label="用户名">
        <el-input v-model="userAccount" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input placeholder="请输入旧密码" v-model="userInfo.oldPassword" autocomplete="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input placeholder="请输入新密码" v-model="userInfo.newPassword" autocomplete="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input placeholder="请再次输入新密码" v-model="userInfo.checkPass" autocomplete="off" show-password></el-input>
      </el-form-item>
    </el-form>
    <div class="form-btn">
      <el-button type="primary" @click="onSubmit" :loading="submitting">提交</el-button>
    </div>
  </div>
</template>
<script>
import { updatePsw } from '@/api/role';
import { getCookie } from "@/utils/support";

export default {
  data () {
    const validPsw = (rule, value, callback) => {
      if (!/^(?:\d|[a-zA-Z]|[!@#$%^&*]){6,32}$/.test(value)) {
        callback(new Error('密码只能包含数字、字母、特殊符号，长度必须6到32个字符之间'));
      }
      callback();
    };
    const validSame = (rule, value, callback) => {
      if (value !== this.userInfo.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      }
      callback();
    };
    return {
      userAccount: '',
      userInfo: {
        oldPassword: '',
        newPassword: '',
        checkPass: '',
      },
      submitting: false,
      rules: {
        oldPassword: [
          {required: true, message: '旧密码必填', trigger: 'blur'},
          {validator: validPsw, trigger: 'blur'},
        ],
        newPassword: [
          {required: true, message: '新密码必填', trigger: 'blur'},
          {validator: validPsw, trigger: 'blur'},
        ],
        checkPass: [
          {required: true, message: '确认密码必填', trigger: 'blur'},
          {validator: validSame, trigger: 'blur'},
        ]
      }
    }
  },
  created () {
    this.userAccount = getCookie("username")
  },
  methods: {
    onSubmit () {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.submitting = true
          updatePsw(this.userInfo).then(() => {
            this.$message.success('更新成功')
          }).catch(() => {
            this.$message.error('更新失败')
          }).finally(() => {
            this.submitting = false
          })
        }
      })
    }
  },
}
</script>
<style scoped>
.change-psw{
  width: 720px;
  margin: 20px auto;
  padding: 35px 35px 15px;
}
.form-btn{
  text-align: center;
  margin-top: 18px;
}
</style>
